<template>
    <div class="add-store">
        <!-- 导航栏 -->
        <tz-breadcrumb  :pathArr='[{"name": "商家"},{"name": "商家列表", "url": "/storeList"},{"name": "添加商户", "url": "/addStore"}]'></tz-breadcrumb>
        <!-- 表单 -->
        <el-form :inline="true" :model="formInline" class="form text-center" label-position="left" label-width="90px" >
          <!-- 步骤条 -->
          <el-steps :active="stepsActive" align-center>
            <el-step title="帐号信息"></el-step>
            <el-step title="商户信息"></el-step>
            <el-step title="成功"></el-step>
          </el-steps>
          <!-- 账户信息 -->
          <div class="step1 step text-left" v-show="stepsActive == 1">
            <div class="step-title">注册管理员帐号</div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="手机号" class="form-item">
                <el-input v-model="formInline.account" placeholder="请输入您的手机号"></el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="图形验证码" class="form-item">
                <el-input placeholder="请输入验证码" v-model="formInline.imgcode" clearable class="" >
                      <template slot="append" >
                        <span v-on:click="changeimg" :class="showImgText?'show-img':'hide'">点击获取图片</span>
                        <img v-bind:src="imgUrl" class="img-path" :class="showImgText?'hide':'show-img'" v-on:click="changeimg"/>
                      </template>
                </el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="验证码" class="form-item">
                <el-input placeholder="请输入验证码" v-model="formInline.code"  clearable>
                      <template slot="append">
                        <input type="button" class=" btn btn-no-bg"  v-bind:disabled="SMSSendClick" v-model="txtusersend" />
                        <div class="img-path send-btn" v-on:click="getCode"></div>
                      </template>
                </el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="密码" class="form-item">
                <el-input type="password" class="passwordInput" v-model="formInline.password" placeholder="密码至少8位，字母、数字、特殊符号（必须包含其中两个）"></el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="确认密码" class="form-item">
                <el-input type="password" class="passwordInput"  v-model="formInline.makePassword" placeholder="请确认密码"></el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="推广人" class="form-item">
                <el-select  v-model="formInline.promoters" placeholder="请选择推广人">
                  <el-option v-for="item in promoterslist" :key="item.id" :label="item.realname" :value="item.identification_code"> </el-option>
                </el-select>
              </el-form-item>
            </div>
            
          </div>
          <!-- 商户信息 -->
          <div class="step1 step text-left" v-show="stepsActive == 2">
            <div class="step-title">商户信息</div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="商户全称" class="form-item">
                <el-input v-model="formInline.name" placeholder="请输入商户全称"></el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="商户简称" class="form-item" >
                <el-input v-model="formInline.short_name" placeholder="请输入商户简称" style="width:150px;"></el-input>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="商户类型" class="form-item">
                <el-select v-model="formInline.storeType" placeholder="请选择 商户类型">
                  <el-option v-for="item in storetypelist" :key="item.store_type" :label="item.store_type_desc" :value="item.store_type"> </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="商户地址" class="form-item">
                <el-cascader :options="options" @change="cityChange" :props='props' expand-trigger="hover"></el-cascader>
              </el-form-item>
            </div>
            <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="具体地址" class="form-item">
                <el-input v-model="formInline.address" placeholder="请填写具体地址"></el-input>
              </el-form-item>
            </div>
             <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="客服电话" class="form-item">
                <el-input v-model="formInline.store_service_tel" placeholder="请输入客服电话"></el-input>
              </el-form-item>
             </div>
             <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="负责人" class="form-item">
                <el-input v-model="formInline.rsmen" placeholder="请输入负责人"></el-input>
              </el-form-item>
             </div>
             <div class="formLineBorder" >
              <span class="starFill" >*</span>
            <el-form-item label="联系电话" class="form-item">
              <el-input v-model="formInline.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
             </div>
             <div class="formLineBorder" >
              <span class="starFill" >*</span>
              <el-form-item label="电子邮箱" class="form-item">
                <el-input v-model="formInline.email" placeholder="请输入电子邮箱"></el-input>
              </el-form-item>
             </div>
          </div>
          <div class="step1 step text-center" v-show="stepsActive == 3">添加成功，请点击完成完成按钮完成配置</div>
          <!-- 横线 -->
          <div class="line"></div>
          <el-row class="next-btn">
            <el-button plain @click="back">返回</el-button>
            <el-button type="primary" @click="next">{{stepsActive == 3 ? '完成' : '下一步'}}</el-button>
          </el-row>
        </el-form>
    </div>
</template>

<script>
import api from './../../api/api';
import http from './../../config/index';
import tzBreadcrumb from './../../components/breadcrumb/breadcrumb.vue';
import CityList from './../../api/city';
export default {
  mounted: function () {
    this.initdata();
  },
  data () {
    return {
      // 当前是第几步
      stepsActive: 1,
      // 发送验证码是否可以点击fales可以点击
      SMSSendClick: false,
      // 发送验证码的文字显示
      txtusersend: '发送验证码',
      // 获取商户类型列表
      storetypelist: [],
      // 显示图片的地址
      imgUrl: '',
      formInline: {
        // 手机号
        account: '',
        // 验证码
        code: '',
        // 密码
        password: '',
        // 图片验证码
        imgcode: '',
        // 对应的图片验证码获取的key值
        verificationKey: '',
        // 确认密码
        makePassword: '',
        // 推荐码
        promoters: '',
        // 商户名称
        name: '',
        // 商家类型
        storeType: '',
        // 省份
        province: '',
        // 城市
        city: '',
        // 区
        district: '',
        // 详细地址
        address: '',
        // 负责人
        rsmen: '',
        // 邮箱
        email: '',
        // 电话
        phone: '',
        // 商户编号
        storeCode: '',
        // 客服电话
        store_service_tel: '',
        // 商户简称
        short_name: ''
      },
      // token值
      token: localStorage.getItem('token'),
      // 点击获取图片的字的显示
      showImgText: true,
      // 推广人
      promoters: [{
        value: '选项1',
        label: '黄金糕'
      }, {
        value: '选项2',
        label: '双皮奶'
      }],
      promoterslist: [],
      options: CityList.CityList,
      props: {
        value: 'value',
        label: 'value',
        children: 'children'
      }
    };
  },
  components: {
    'tz-breadcrumb': tzBreadcrumb
  },
  methods: {
    initdata: function () {
      let that = this;
      that.page = 1;
      that.getData();
    },
    // 城市改变
    cityChange (val) {
      console.log(val);
      let that = this;
      that.formInline.province = val[0];
      that.formInline.city = val[1];
      that.formInline.district = val[2];
    },
    getData () {
      let that = this;
      http.post(api.member, {
        token: localStorage.getItem('token')
      }, response => {
        console.log(response.data.result);
        if (response.code === '10001') {
          that.promoterslist = response.data;
        } else {
          that.$message.error(response.msg);
          // that.promoterslist = response.data;
        }
      }, () => {
        console.log('网络错误');
        that.$message.error('网络错误,请稍后再试');
      });
    // 获取商户类型列表
      http.get(api.getStoreTypeList, {
        token: localStorage.getItem('token')
      }, response => {
        console.log(response.data.result);
        if (response.code === '10001') {
          that.storetypelist = response.data[0].result;
        }
      }, () => {
        console.log('网络错误');
      });
    },
    next () {
      let that = this;
      // 第一步的验证
      // 验证密码至少8位，字母、数字、特殊符号（必须包含其中两个）
      var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[\w~!@#$%^&*()_+`\-={}:";'<>?,./]{8,}$/;
      // 邮箱验证
      var emailReg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
      // 手机号码格式规范
      // var mobilephoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
      var mobilephoneReg = /^1[34578]\d{9}$/;
      if (this.stepsActive === 1) {
        if (that.formInline.account === '') {
          that.$message.error('手机号不能为空');
          return false;
        } else if (!mobilephoneReg.test(that.formInline.account)) {
          that.$message.error('手机号格式不正确');
          return false;
        } else if (that.formInline.code === '') {
          that.$message.error('验证码不能为空');
          return false;
        } else if (that.formInline.password === '') {
          that.$message.error('密码不能为空');
          return false;
        } else if (!reg.test(that.formInline.password)) {
          that.$message.error('密码至少8位，字母、数字、特殊符号（必须包含其中两个）');
          return false;
        } else if (that.formInline.makePassword === '') {
          that.$message.error('确认密码不能为空');
          return false;
        } else if (that.formInline.password !== that.formInline.makePassword) {
          that.$message.error('确认密码和密码不一致');
          return false;
        } else if (that.formInline.promoters === '') {
          that.$message.error('推广人不能为空');
          return false;
        }
        // 跳转下一步
        that.stepsActive = this.stepsActive + 1;
        return true;
      } else if (this.stepsActive === 2) {
        // 第二步的验证
        if (that.formInline.name === '') {
          that.$message.error('商家名称不能为空');
          return false;
        } else if (that.formInline.short_name === '') {
          that.$message.error('商家简称不能为空');
          return false;
        } else if (that.formInline.storeType === '') {
          that.$message.error('商家类型不能为空');
          return false;
        } else if (that.formInline.province === '') {
          that.$message.error('请选择所在省份');
          return false;
        } else if (that.formInline.city === '') {
          that.$message.error('请选择所在城市');
          return false;
        } else if (that.formInline.district === '') {
          that.$message.error('请选择所在县市');
          return false;
        } else if (that.formInline.address === '') {
          that.$message.error('请填写详细地址');
          return false;
        } else if (that.formInline.store_service_tel === '') {
          that.$message.error('请填写客服电话');
          return false;
        } else if (that.formInline.rsmen === '') {
          that.$message.error('请填写负责人');
          return false;
        } else if (that.formInline.phone === '') {
          that.$message.error('请填写电话');
          return false;
        } else if (!mobilephoneReg.test(that.formInline.phone)) {
          that.$message.error('手机格式不正确');
          return false;
        } else if (that.formInline.email === '') {
          that.$message.error('请填写邮箱');
          return false;
        } else if (!emailReg.test(that.formInline.email)) {
          that.$message.error('邮箱格式不正确');
          return false;
        }
        // 跳转下一步
        that.stepsActive = this.stepsActive + 1;
      } else {
        let that = this;
        new Promise((resolve, reject) => {
          // 商户注册请求接口
          http.post(api.merchantCreate, {
            token: that.token,
            mobile: that.formInline.account,
            mobile_check_code: that.formInline.code,
            password: that.formInline.password,
            password_confirmation: that.formInline.makePassword,
            // 推荐码
            promotion_code: that.formInline.promoters
          }, (res) => {
            if (res.code === '10001' && res.status === 'SUCCESS') {
              // 获取对应的商户编号
              that.formInline.storeCode = res.data[0].store_code;
              resolve(1);
              return false;
            };
            that.$message.error(res.msg);
            reject(2);
          }, () => {
            that.$message.error('网络错误，请稍候再试');
          });
        }).then((data) => {
          // 商户基本资料填写与修改接口请求
          http.post(api.merchantCreateDetails, {
            token: that.token,
            store_code: that.formInline.storeCode,
            store_name: that.formInline.name,
            store_type: that.formInline.storeType,
            province: that.formInline.province,
            city: that.formInline.city,
            district: that.formInline.district,
            address: that.formInline.address,
            // 负责人
            contact_name: that.formInline.rsmen,
            contact_phone: that.formInline.phone,
            contact_email: that.formInline.email,
            store_service_tel: that.formInline.store_service_tel,
            short_name: that.formInline.short_name
          }, (res) => {
            if (res.code === '10001' && res.status === 'SUCCESS') {
              that.$message.success('添加商户成功');
              this.$router.push({
                path: '/store-list'
              });
              return false;
            };
            that.$message.error(res.msg);
          }, () => {
            that.$message.error('网络错误，请稍候再试');
          });
        }, (err) => {
          console.log(err);
        });
      }
    },
    back () {
      if (this.stepsActive > 1) {
        this.stepsActive = this.stepsActive - 1;
      };
    },
    // 获取图形验证码
    changeimg () {
      console.log(1);
      let that = this;
      http.get(api.captcha, {}, (res) => {
        console.log(res);
        if (res.code === '10001' && res.status === 'SUCCESS') {
          // 点击发送图片不显示
          that.showImgText = false;
          // 获取对应的图片src路径
          that.imgUrl = res.data[0].captcha_image_content;
          // 获取对应的验证码key值
          that.formInline.verificationKey = res.data[0].captcha_key;
          return false;
        };
        that.$message.error(res.msg);
      }, () => {
        that.$message.error('网络错误，请稍候再试');
      });
      return true;
    },
    // 发送短信验证码
    getCode () {
      let that = this;
      if (that.SMSSendClick === true) {
        return false;
      }
      // 手机号码格式规范
      var mobilephoneReg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (that.formInline.account === '') {
        that.$message.error('手机号不能为空');
        return false;
      } else if (!mobilephoneReg.test(that.formInline.account)) {
        that.$message.error('手机号格式不正确');
        return false;
      } else if (that.formInline.imgcode === '') {
        that.$message.error('图形验证码不能为空');
        return false;
      }
      // 初始化60s
      var second = 60;

      http.get(api.sendsms, {mobile: that.formInline.account, verification_code: that.formInline.imgcode, verification_key: that.formInline.verificationKey}, (res) => {
        console.log(res);
        if (res.code === '10001' && res.status === 'SUCCESS') {
          // 发送验证码不能点击状态, 倒计时60s, 否则可以点击, 恢复为发送验证码，清除定时器
          that.SMSSendClick = true;
          that.$message.success('短信发送成功，请注意查收');
          var time = setInterval(function () {
            if (second > 0) {
              that.txtusersend = '剩余' + second + '秒';
              second--;
              console.log(that.txtusersend);
            } else {
              that.SMSSendClick = false;
              that.txtusersend = '发送验证码';
              // 清除定时器
              clearInterval(time);
            }
          }, 1000);
          return false;
        };
        that.$message.error(res.msg);
      }, () => {
        that.$message.error('网络错误，请稍候再试');
      });
      return true;
    }
  }
};
</script>

<style lang="stylus" scoped>
.form
  padding: 2rem
  margin-top: 15px
  margin-bottom: 12px
  box-sizing: border-box
  background: #fff
  .step
    margin: 55px 0;
    width: 600px;
    display: inline-block
    .step-title
      border-left: 5px solid #36ADCB
      padding-left: 5px
      font-size: 16px
      margin-bottom: 15px;
  .line
    border-top: 1px solid #ABABAB;
  .next-btn
    padding-top: 25px
.formLineBorder
  position: relative
  margin-left:10px
  .starFill
    position: absolute;
    top: 12px;
    left: -10px;
    color: #f00
    font-size: 14px
  .form-item
    display: block
    .img-path
      width: 125px
      height: 39px
      position: absolute
      top: 0
      left: 0
      cursor: pointer
    .send-btn
      width:111px
    .show-img
      opacity: 1
    .hide
      opacity: 0
    .btn-no-bg
      background: none
    .passwordInput
      width: 400px
</style>
